import { createStore, useStore as useVueStore } from 'vuex'
import type { TRootState, IStoreType } from './type'
import login from './login/login'
import system from './main/system/system'
import dashboard from './main/analysis/dashboard'
import type { Store } from 'vuex'
import { getPageListData } from '@/service/main/system/system'

const store = createStore<TRootState>({
  state: {
    name: 'kzj',
    entireDepartment: [],
    entireRole: [],
    entireMenu: []
  },
  mutations: {
    changeEntireDepartment(state, list) {
      state.entireDepartment = list
    },
    changeEntireRole(state, list) {
      state.entireRole = list
    },
    changeEntireMenu(state, list) {
      state.entireMenu = list
    }
  },
  getters: {},
  actions: {
    async getInitialDataAction({ commit }) {
      // 1.请求部门页和角色页的数据
      const departmentResult = await getPageListData('/department/list', {
        offset: 0,
        size: 1000
      })
      const { list: departmentList } = departmentResult.data
      const roleResult = await getPageListData('/role/list', {
        offset: 0,
        size: 1000
      })
      const { list: roleList } = roleResult.data
      const menuResult = await getPageListData('/menu/list', {})
      const { list: menuList } = menuResult.data

      // 2.保存数据
      commit('changeEntireDepartment', departmentList)
      commit('changeEntireRole', roleList)
      commit('changeEntireMenu', menuList)
    }
  },
  modules: {
    login,
    system,
    dashboard
  }
})

//初始化本地数据与vuex数据联系
//防止刷新后vuex数据脱失 需要在main.ts中使用
export function setupStore() {
  store.dispatch('login/loadLocalLogin')
  // store.dispatch('getInitialDataAction') //初始化部门和角色信息(需要在拿到token后执行！！！)
}

//重写userStore增加模块类型
export function useStore(): Store<IStoreType> {
  return useVueStore()
}

export default store
